"""会话服务层

处理脑波会话的业务逻辑
包括会话的创建、更新、查询等操作
"""

import uuid
from datetime import datetime
from typing import Optional, Dict, List
from loguru import logger
from app.models.brain_wave import BrainWave
from app.core.database import database


class SessionService:
    """会话服务类
    
    处理脑波会话相关的业务逻辑
    提供会话的CRUD操作和状态管理
    """
    
    async def create_session(self, room_id: str, user_id: Optional[str] = None) -> dict:
        """创建新会话
        
        Args:
            room_id: 房间ID
            user_id: 用户ID（可选）
            
        Returns:
            dict: 创建的会话信息
        """
        try:
            # 创建脑波记录，不再传递id参数，让数据库自动生成
            brain_wave = BrainWave.create_session(
                room_id=room_id,
                user_id=user_id
            )
            
            logger.info(f"会话创建成功: {brain_wave.id}")
            return {
                "id": brain_wave.id,
                "room_id": room_id,
                "user_id": user_id,
                "start_time": brain_wave.start_time.isoformat(),
                "total_seconds": 0
            }
            
        except Exception as e:
            logger.error(f"创建会话失败: {str(e)}")
            # 如果是数据库连接问题，返回更友好的错误信息
            if "Access denied" in str(e) or "Connection refused" in str(e):
                raise Exception("数据库连接失败，请检查数据库配置")
            raise
    
    async def get_session(self, id: str) -> Optional[dict]:
        """获取会话信息
        
        Args:
            id: 会话ID（现在使用id字段）
            
        Returns:
            dict: 会话信息，不存在则返回None
        """
        try:
            brain_wave = BrainWave.get_or_none(BrainWave.id == id)
            if brain_wave:
                # 安全处理时间字段
                def format_time(time_field):
                    if time_field is None:
                        return None
                    if isinstance(time_field, datetime):
                        return time_field.isoformat()
                    return str(time_field)
                
                return {
                    "id": brain_wave.id,
                    "room_id": brain_wave.room_id,
                    "user_id": brain_wave.user_id,
                    "start_time": format_time(brain_wave.start_time),
                    "end_time": format_time(brain_wave.end_time),
                    "total_seconds": brain_wave.total_seconds,
                    "created_at": format_time(brain_wave.created_at)
                }
            return None
            
        except Exception as e:
            logger.error(f"获取会话失败: {str(e)}")
            raise
    
    async def update_session(self, id: str, update_data: dict) -> Optional[dict]:
        """更新会话信息
        
        Args:
            id: 会话ID（现在使用id字段）
            update_data: 更新的数据字典
            
        Returns:
            dict: 更新后的会话信息，不存在则返回None
        """
        try:
            # 先检查会话是否存在
            brain_wave = BrainWave.get_or_none(BrainWave.id == id)
            if not brain_wave:
                return None
            
            # 执行更新
            query = BrainWave.update(**update_data).where(BrainWave.id == id)
            rows_updated = query.execute()
            
            if rows_updated > 0:
                logger.info(f"会话更新成功: {id}")
                # 重新获取更新后的数据
                return await self.get_session(id)
            else:
                return None
                
        except Exception as e:
            logger.error(f"更新会话失败: {str(e)}")
            raise
    
    async def get_active_sessions(self) -> List[dict]:
        """获取活跃会话列表
        
        Returns:
            List[dict]: 活跃会话列表
        """
        try:
            # 获取未结束的会话（end_time为空）
            active_sessions = BrainWave.select().where(BrainWave.end_time.is_null())
            
            result = []
            for session in active_sessions:
                session_dict = session.to_dict()
                # 计算当前会话时长
                if session.start_time:
                    current_seconds = int((datetime.now() - session.start_time).total_seconds())
                    session_dict['current_duration'] = current_seconds
                result.append(session_dict)
            
            return result
            
        except Exception as e:
            logger.error(f"获取活跃会话失败: {str(e)}")
            raise
    
    async def delete_session(self, id: str) -> bool:
        """删除会话
        
        Args:
            id: 会话ID（现在使用id字段）
            
        Returns:
            bool: 删除是否成功
        """
        try:
            query = BrainWave.delete().where(BrainWave.id == id)
            rows_deleted = query.execute()
            
            if rows_deleted > 0:
                logger.info(f"会话删除成功: {id}")
                return True
            else:
                logger.warning(f"会话不存在: {id}")
                return False
                
        except Exception as e:
            logger.error(f"删除会话失败: {str(e)}")
            raise